package com.nys.cqhttp.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.common.Choice;
import com.unfbx.chatgpt.entity.completions.CompletionResponse;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import okhttp3.*;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.nys.cqhttp.config.NamedThreadFactory;
import com.nys.cqhttp.constant.CommonConstant;
import com.nys.cqhttp.param.MessageParam;
import com.nys.cqhttp.service.IMsgService;
import com.nys.cqhttp.util.RequestUtil;
import org.springframework.web.client.RestTemplate;

/**
 * IndexController
 *
 * @author nysheng
 * @version 1.0.0
 * @description 就一个接口，只需要提供一个接口给go-cqhttp调用
 * @date 2021/12/27 13:40
 */
@RestController
public class IndexController {

  @Autowired private Map<String, IMsgService> msgServiceMap;
  @Autowired private RestTemplate restTemplate;
  private static Map<String, String> msgServiceNameMap;

  private static ExecutorService threadPool =
      new ThreadPoolExecutor(
          4,
          6,
          60,
          TimeUnit.SECONDS,
          new ArrayBlockingQueue<>(1024),
          new NamedThreadFactory("pool-thread-cqhttp", false));

  static {
    msgServiceNameMap = new HashMap<>();
    msgServiceNameMap.put(CommonConstant.STR_PRIVATE, "privateMsgServiceImpl");
    msgServiceNameMap.put(CommonConstant.STR_GROUP, "groupMsgServiceImpl");
  }

  @PostMapping("/")
  public String post(HttpServletRequest request) {
    MessageParam messageParam = RequestUtil.getMessageParam(request);
    String handlerName = msgServiceNameMap.get(messageParam.getMessageType());
    if (StringUtils.isNotEmpty(handlerName)) {
      threadPool.execute(() -> msgServiceMap.get(handlerName).start(messageParam));
    }
    return "ok";
  }
}
